package com.v2future.sjt.collegecheckingattendance.utils.netutils;

import android.content.Context;
import android.content.res.Configuration;

import com.google.gson.Gson;
import com.v2future.sjt.collegecheckingattendance.MainActivity;
import com.v2future.sjt.collegecheckingattendance.utils.BaseResponseBean;
import com.v2future.sjt.collegecheckingattendance.utils.GsonUtil;
import com.v2future.sjt.collegecheckingattendance.utils.LogUtils;

import org.xutils.common.Callback;
import org.xutils.ex.HttpException;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;
import java.net.URLDecoder;

/**
 * Created by minnie on 16/1/7.
 */
public class NetUtils {

    public static Callback.Cancelable cancelable;

    public static final String FLAG_SUCCESS = "1";

    /**
     * get请求
     * @param params
     * @param netTaskListener
     * @param <T>
     */
    public static <T> void doGetRequestBase(Context context, RequestParams params,
                                            final boolean isUseCache,
                                            final NetTaskListener<T> netTaskListener){
            LogUtils.d(LogUtils.TAG, "发送地址："+params.toString());
            for (int i=0;i<params.getQueryStringParams().size();i++) {
                LogUtils.d(LogUtils.TAG, "参数"+i+":"+params.getQueryStringParams().get(i).key+"-"+params.getQueryStringParams().get(i).getValueStr());
            }
            final MainActivity mainActivity = (MainActivity) context;
            cancelable = x.http().get(params, new Callback.CacheCallback<String>() {
                @Override
                public void onSuccess(String result) {
                    try {
                        result = URLDecoder.decode(result, "UTF-8");
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                    LogUtils.dJson(LogUtils.TAG, result.toString(), "收到的回复");
                    T resultBean = GsonUtil.fromJsonStringToCollection(
                            result.toString(), netTaskListener.getType());
                    BaseResponseBean baseBean = (BaseResponseBean) resultBean;
                    //如果所属Activity已经结束，则不返回请求
                    if (mainActivity.isOver()) return;
                    if (null != baseBean && FLAG_SUCCESS.equals(baseBean.getFlag())) {
                        netTaskListener.onSuccess(resultBean);
                    }
                    else {
                        netTaskListener.onInterError(resultBean);
                    }
                }

                @Override
                public void onError(Throwable ex, boolean isOnCallback) {
                    if (ex instanceof HttpException) { // 网络错误
                        HttpException httpEx = (HttpException) ex;
                        int responseCode = httpEx.getCode();
                        String responseMsg = httpEx.getMessage();
                        String errorResult = httpEx.getResult();
                        LogUtils.d(LogUtils.TAG, "网络错误");
                        //如果所属Activity已经结束，则不返回请求
                        if (mainActivity.isOver()) return;
                        netTaskListener.onNetError(responseCode, responseMsg, errorResult);
                        // ...
                    } else { // 其他错误
                        // ...
                        ex.printStackTrace();
                        //如果所属Activity已经结束，则不返回请求
                        if (mainActivity.isOver()) return;
                        netTaskListener.onError();
                    }
                }

                @Override
                public void onCancelled(CancelledException cex) {
                    LogUtils.d(LogUtils.TAG, "网络取消");
                    netTaskListener.onCancelled();
                }

                @Override
                public void onFinished() {
                    //如果所属Activity已经结束，则不返回请求
                    if (mainActivity.isOver()) return;
                    netTaskListener.onFinished();
                }

                @Override
                public boolean onCache(String result) {
//                    LogUtils.dJson(LogUtils.TAG, result.toString(), "收到缓存");
                    T resultBean = GsonUtil.fromJsonStringToCollection(
                            result.toString(), netTaskListener.getType());
                    netTaskListener.onSuccessCache(resultBean);
                    return isUseCache;//是否信任缓存，true信任缓存，不发送网络请求
                }
            });
    }

    public static <T> void doPostRequestWithFiles(Context context, RequestParams params, final NetTaskListener<T> netTaskListener){
        final MainActivity mainActivity = (MainActivity) context;
        LogUtils.d(LogUtils.TAG, "发送地址："+params.toString());
        for (int i=0;i<params.getQueryStringParams().size();i++) {
            LogUtils.d(LogUtils.TAG, "参数"+i+":"+params.getQueryStringParams().get(i).key+"-"+params.getQueryStringParams().get(i).getValueStr());
        }
        cancelable = x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                try {
                    result = URLDecoder.decode(result, "UTF-8");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                LogUtils.dJson(LogUtils.TAG, result.toString(), "收到的回复");
                T resultBean = GsonUtil.fromJsonStringToCollection(
                        result.toString(), netTaskListener.getType());
                BaseResponseBean baseBean = (BaseResponseBean) resultBean;
                //如果所属Activity已经结束，则不返回请求
                if (mainActivity.isOver()) return;
                if (null != baseBean && FLAG_SUCCESS.equals(baseBean.getFlag())) {
                    netTaskListener.onSuccess(resultBean);
                }
                else {
                    netTaskListener.onInterError(resultBean);
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                if (ex instanceof HttpException) { // 网络错误
                    HttpException httpEx = (HttpException) ex;
                    int responseCode = httpEx.getCode();
                    String responseMsg = httpEx.getMessage();
                    String errorResult = httpEx.getResult();
                    LogUtils.d(LogUtils.TAG, "网络错误");
                    //如果所属Activity已经结束，则不返回请求
                    if (mainActivity.isOver()) return;
                    netTaskListener.onNetError(responseCode, responseMsg, errorResult);
                    // ...
                } else { // 其他错误
                    // ...
                    ex.printStackTrace();
                    //如果所属Activity已经结束，则不返回请求
                    if (mainActivity.isOver()) return;
                    netTaskListener.onError();
                }
            }

            @Override
            public void onCancelled(CancelledException cex) {
                LogUtils.d(LogUtils.TAG, "网络取消");
                netTaskListener.onCancelled();
            }

            @Override
            public void onFinished() {
                //如果所属Activity已经结束，则不返回请求
                if (mainActivity.isOver()) return;
                netTaskListener.onFinished();
            }

        });
    }

    /**
     * 只有缓存的get请求
     * @param params
     * @param netTaskListener
     * @param <T>
     */
    public static <T> void doGetRequestCatheOnly(Context context, RequestParams params, final NetTaskListener<T> netTaskListener){
        doGetRequestBase(context, params, true, netTaskListener);
    }

    /**
     * 普通的get请求
     * @param params
     * @param netTaskListener
     * @param <T>
     */
    public static <T> void doGetRequest(Context context, RequestParams params, final NetTaskListener<T> netTaskListener){
        doGetRequestBase(context, params, false, netTaskListener);
    }

    public static void doPostRequest(NetTaskListener netTaskListener){

    }

    /**
     * 取消网络请求
     */
    public static void cancelRequest(){
        if (null != cancelable) {
            cancelable.cancel();
        }
    }
}
